package com.glela.live.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.glela.cache.model.RedisKey;
import com.glela.cache.redis.RedisUtil;
import com.glela.common.constant.CommonConstants;
import com.glela.common.util.StringUtils;
import com.glela.live.mapper.LiveShareClickRecordMapper;
import com.glela.live.model.LivePlan;
import com.glela.live.model.LiveShareClickRecord;
import com.glela.live.model.ShareRankingListVo;
import com.glela.live.service.LivePlanService;
import com.glela.live.service.LiveShareClickRecordService;
import com.glela.packet.enums.RedPacketEventTypeEnum;
import com.glela.platform.model.User;
import com.glela.platform.service.UserService;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * Created by jinweiwei on 2018/4/16.
 */
@Service
public class LiveShareClickRecordServiceImpl implements LiveShareClickRecordService{

    @Autowired
    private LivePlanService livePlanService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private LiveShareClickRecordMapper liveShareClickRecordMapper;

    @Resource(name = "liveShareRedPackageTemplates")
    private AmqpTemplate liveShareRedPackageTemplates;

    @Autowired
    private UserService userService;

    @Override
    public int add(LiveShareClickRecord liveShareClickRecord) {
        LivePlan livePlan = livePlanService.getById(liveShareClickRecord.getLivePlanId());
        if (livePlan!=null && livePlan.getStatus()==2){
            User user = userService.getUserById(Long.valueOf(liveShareClickRecord.getUserId()));
            if (user!=null && (user.getRoleId()==1 || user.getRoleId()==2)){
                try {
//                    Object object = redisUtil.eval(CommonConstants.liveShareSendRedPackage, 2, RedisKey.REDIS_SHARE_SEND_REDPACKAGE_SET + liveShareClickRecord.getLivePlanId(), liveShareClickRecord.getUserId() + "");
                    Object object = redisUtil.eval(CommonConstants.liveUserShareSetScript,10,RedisKey.REDIS_SHARE_LIVE_USER_SET+liveShareClickRecord.getLivePlanId()+":"+liveShareClickRecord.getShareUserId(),liveShareClickRecord.getUserId()+"",RedisKey.REDIS_OWN_SHARE_COUNT+liveShareClickRecord.getLivePlanId()+":"+liveShareClickRecord.getShareUserId(),CommonConstants.RANKING_NUM+"",CommonConstants.RANKING_MAX_TIME+"",System.currentTimeMillis()+"",RedisKey.REDIS_SHARE_LIVE_LAST_CLICK_TIME+liveShareClickRecord.getLivePlanId()+":"+liveShareClickRecord.getShareUserId(),RedisKey.REDIS_SHARE_RANKING_LIST+liveShareClickRecord.getLivePlanId(),liveShareClickRecord.getShareUserId()+"",RedisKey.REDIS_SHARE_SEND_REDPACKAGE_SET + liveShareClickRecord.getLivePlanId());
                    if (1==(long)object){
                        JSONObject json = new JSONObject();
                        json.put("receiveUserId",liveShareClickRecord.getShareUserId());
                        json.put("eventType", RedPacketEventTypeEnum.LIVE_SHARE_AWARD.getType());
                        liveShareRedPackageTemplates.convertAndSend("liveShareRedPackage",json);
                    }

                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            return liveShareClickRecordMapper.add(liveShareClickRecord);
        }
        return 0;
    }

//    private static ExecutorService executorService	= Executors.newFixedThreadPool(5);

    @Override
    public List<ShareRankingListVo> getShareRankingList(int livePlanId, int userId) {
        /*if (StringUtils.isEmpty(redisUtil.get(RedisKey.REDIS_SHARE_RANKING_LIST_EXPIRE+livePlanId))){
            //获取最新的排行版并更新缓存
            if (StringUtils.isEmpty(redisUtil.get(RedisKey.REDIS_SHARE_RANKING_LIST+livePlanId))){
                List<ShareRankingListVo> list = liveShareClickRecordMapper.getShareRankingList(livePlanId);
                if (list!=null && !list.isEmpty()){
                    for (ShareRankingListVo s:list) {
                        s.setUserName(s.getUserName().substring(7,11));
                        if (StringUtils.isEmpty(s.getNickName())){
                            s.setNickName("铺**");
                        }else{
                            s.setNickName(s.getNickName().substring(0,1)+"**");
                        }
                        if (userId!=0 && userId==s.getUserId()){
                            s.setOwnFlag(1);
                        }
                    }
                    redisUtil.set(RedisKey.REDIS_SHARE_RANKING_LIST+livePlanId,list);
                }
                redisUtil.set(RedisKey.REDIS_SHARE_RANKING_LIST_EXPIRE+livePlanId,"1",10);
                return list;
            }else{
                String str = redisUtil.get(RedisKey.REDIS_SHARE_RANKING_LIST+livePlanId);
                if (!StringUtils.isEmpty(str)){
                    List<ShareRankingListVo> list = JSONObject.parseArray(str,ShareRankingListVo.class);
                    for (ShareRankingListVo s: list) {
                        if (userId!=0 && userId==s.getUserId()){
                            s.setOwnFlag(1);
                        }
                    }
                    cacheShareRankingList(livePlanId);
                    return list;
                }
                return new ArrayList<>();
            }
        }else{
            String str = redisUtil.get(RedisKey.REDIS_SHARE_RANKING_LIST+livePlanId);
            if (!StringUtils.isEmpty(str)) {
                List<ShareRankingListVo> list = JSONObject.parseArray(str, ShareRankingListVo.class);
                for (ShareRankingListVo s: list) {
                    if (userId!=0 && userId==s.getUserId()){
                        s.setOwnFlag(1);
                    }
                }
                return list;
            }
            return new ArrayList<>();
        }*/

        Set<String> set = redisUtil.zrevrange(RedisKey.REDIS_SHARE_RANKING_LIST+livePlanId,0,5);
        if (set.isEmpty()){
            return new ArrayList<>();
        }
        List<ShareRankingListVo> list = new ArrayList<>(set.size());
        for (String s:set){
            ShareRankingListVo shareRankingListVo = new ShareRankingListVo();
            User user = userService.getUserById(Long.valueOf(s));
            shareRankingListVo.setNickName(user==null?"铺**":(StringUtils.isEmpty(user.getNickName())?"铺**":(user.getNickName().substring(0,1)+"**")));
            shareRankingListVo.setUserName(user==null?"":(StringUtils.isEmpty(user.getUserName())?"":(user.getUserName().substring(7,11))));
            if (userId!=0 && userId==user.getId()) {
                shareRankingListVo.setOwnFlag(1);
            }
            shareRankingListVo.setPicture(user==null?"":user.getPicture());
            shareRankingListVo.setUserId(user.getId().intValue());
            shareRankingListVo.setCount(StringUtils.isEmpty(redisUtil.get(RedisKey.REDIS_OWN_SHARE_COUNT+livePlanId+":"+user.getId()))?0:Integer.valueOf(redisUtil.get(RedisKey.REDIS_OWN_SHARE_COUNT+livePlanId+":"+user.getId())));
            list.add(shareRankingListVo);
        }
        return list;

    }

    @Override
    public int getshareCountByUid(int livePlanId,int userId) {
//        if (StringUtils.isEmpty(redisUtil.get(RedisKey.REDIS_OWN_SHARE_COUNT_EXPIRE+livePlanId+":"+userId))){
        if (StringUtils.isEmpty(redisUtil.get(RedisKey.REDIS_OWN_SHARE_COUNT+livePlanId+":"+userId))){
            /*int count = liveShareClickRecordMapper.getShareCountByUid(livePlanId,userId);
            redisUtil.set(RedisKey.REDIS_OWN_SHARE_COUNT+livePlanId+":"+userId,count);
            redisUtil.set(RedisKey.REDIS_OWN_SHARE_COUNT_EXPIRE+livePlanId+":"+userId,"1",10);*/
            return 0;
        }else{
            String str = redisUtil.get(RedisKey.REDIS_OWN_SHARE_COUNT+livePlanId+":"+userId);
            int count = Integer.valueOf(str);
//                cacheShareCount(livePlanId,userId);
            return count;
        }
       /* }else{
            String str = redisUtil.get(RedisKey.REDIS_OWN_SHARE_COUNT+livePlanId+":"+userId);
            int count = Integer.valueOf(str);
            return count;
        }*/
    }
/*
    private void cacheShareCount(final int livePlanId,final int userId) {
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                int count = liveShareClickRecordMapper.getShareCountByUid(livePlanId,userId);
                redisUtil.set(RedisKey.REDIS_OWN_SHARE_COUNT+livePlanId+":"+userId,count);
                redisUtil.set(RedisKey.REDIS_OWN_SHARE_COUNT_EXPIRE+livePlanId+":"+userId,"1",10);
            }
        });
    }*/

    /*public void cacheShareRankingList(final int livePlanId) {
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                List<ShareRankingListVo> list = liveShareClickRecordMapper.getShareRankingList(livePlanId);
                if (list!=null && !list.isEmpty()){
                    for (ShareRankingListVo s:list) {
                        s.setUserName(s.getUserName().substring(7,11));
                        if (StringUtils.isEmpty(s.getNickName())){
                            s.setNickName("铺**");
                        }else{
                            s.setNickName(s.getNickName().substring(0,1)+"**");
                        }
                    }
                    redisUtil.set(RedisKey.REDIS_SHARE_RANKING_LIST+livePlanId,list);
                }
                redisUtil.set(RedisKey.REDIS_SHARE_RANKING_LIST_EXPIRE+livePlanId,"1",10);
            }
        });
    }*/
}
